package com.atgugu.flink.chapter08;

import com.atgugu.flink.bean.UserBehavior;
import com.atgugu.flink.util.AtguiguUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

/**
 * @Author lzc
 * @Date 2022/4/8 9:00
 * private Long userId;
 * private Long itemId;
 * private Integer categoryId;
 * private String behavior;
 * private Long timestamp;
 */
public class Flink02_Project_High_Uv {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
    
        env
            .readTextFile("input/UserBehavior.csv")
            .map(line -> {
                String[] data = line.split(",");
                return new UserBehavior(
                    Long.valueOf(data[0]),  // 得到的是包装类型
                    Long.valueOf(data[1]),
                    Integer.valueOf(data[2]),
                    data[3],
                    Long.parseLong(data[4]) * 1000
                );
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((ub, ts) -> ub.getTimestamp())
            )
            .filter(ub -> "pv".equals(ub.getBehavior()))
            .keyBy(UserBehavior::getBehavior)
            .window(TumblingEventTimeWindows.of(Time.hours(1)))
            .process(new ProcessWindowFunction<UserBehavior, String, String, TimeWindow>() {
    
                private MapState<Long, Object> userIdsState;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    // 键控状态只和key有关
                    userIdsState = getRuntimeContext().getMapState(new MapStateDescriptor<Long, Object>("userIdsState", Long.class, Object.class));
                }
    
                @Override
                public void process(String key,
                                    Context ctx,
                                    Iterable<UserBehavior> elements,
                                    Collector<String> out) throws Exception {
                    // 先清空状态
                    userIdsState.clear();
                    
                    // 计算每个窗口内的uv
                    // 把userId存入到状态中, userId是map中的key, 有多少个key, uv就是几
                    for (UserBehavior element : elements) {
                        userIdsState.put(element.getUserId(), new Object());
                    }
    
                    List<Long> userIdList = AtguiguUtil.toList(userIdsState.keys());
                    
                    out.collect(ctx.window() + " uv=" + userIdList.size());
    
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
